#include <myhead.h>
#include "service.h"
#include "mypkg.h"

int ssh_service_ssh(char* cmd, char* sendbuf, int* bufLen){
	//创建一个无名管道
	int pipefd[2];
	pipe(pipefd);
	
	//拆解指令
	printf("用户指令,cmd=[%s]\n", cmd);
	char* arg[64]={0};
	arg[0]=strtok(cmd, " ");
	for(int i=1;i<64;i++){
		arg[i]=strtok(NULL, " ");
		if(arg[i] == NULL)
			break;
		printf("[%d]:%s\n", i, arg[i]);
	}

	//fork然后立马exec一个进程
	pid_t pid=fork();
	if(pid==0){//子进程
		close(pipefd[0]);
		dup2(pipefd[1], 1);
		dup2(pipefd[1], 2);
		close(pipefd[1]);
		execvp(arg[0], arg);
	}
	//父进程
	close(pipefd[1]);
	char buf[1024]={0};
	ssize_t cnt=read(pipefd[0], buf, sizeof(buf));
	printf("读取到子进程执行结果[%ld]:%s\n", cnt, buf);
	close(pipefd[0]);
	waitpid(pid, NULL, 0);

	//组装返回报文
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 2,"OK", buf);
	return 0;
}

int ssh_service_upload_start(char* username, char* dest,char* sendbuf, int* bufLen){
	//将文件名补充完整
	char filename[256]="./file/";
	strcat(filename, dest);
	printf("filename=[%s]\n", filename);
	//以truncat的方式创建文件
	FILE* fp=fopen(filename, "w");
	fclose(fp);
	//组装返回报
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 1, "OK");
	return 0;
}

int ssh_service_upload_content(char* username, char* dest,char* content,int contentLen,char* sendbuf, int* bufLen){
	//打开文件(以append的方式打开)
	char filename[256]="./file/";
	strcat(filename, dest);
	printf("filename=[%s]\n", filename);
	FILE* fp=fopen(filename, "a");	

	//写入文件
	size_t cnt=fwrite(content, 1, contentLen, fp);
	printf("写入了文件[%s]:[%ld]\n", filename, cnt);
	
	//关闭文件
	fclose(fp);

	//组装返回报
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 1, "OK");
	return 0;
}


int ssh_service_upload_end(char* username, char* dest,char* sendbuf, int* bufLen){
	//组装返回报
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 1, "OK");
	return 0;
}


int ssh_service_download_start(char* username, char* filename, char* sendbuf, int* bufLen){
	//将文件名补充完整
	printf("download_start:filename=[%s]\n", filename);
	//文件是否存在
	if(access(filename, F_OK) != 0){
		//组装返回报
		*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 2, "ERROR", "服务端该文件不存在");
		return -1;
	}
	//组装返回报
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 1, "OK");
	return 0;
}

int ssh_service_download_content(char* username, char* filename,long start, char* sendbuf, int* bufLen){
	//打开文件(以append的方式打开)
	//char filename[256]="./file/";
	//strcat(filename, dest);
	printf("download_content:filename=[%s]\n", filename);
	FILE* fp=fopen(filename, "r");	
	//移动指针
	fseek(fp, start,SEEK_SET);
	//读文件
	char buf[1024]={0};
	size_t readCnt=fread(buf, 1, sizeof(buf), fp);

	//组包
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 1, "OK");
	*bufLen = pkg_appendByteArr(sendbuf, buf, readCnt);
	fclose(fp);
	return 0;
}


int ssh_service_download_end(char* username, char* dest,char* sendbuf, int* bufLen){
	//组装返回报
	*bufLen = pkg_pack_buf(sendbuf, MSG_TYPE_RET, 1, "OK");
	return 0;
}








